package com.example.statistics.common

import android.Manifest
import android.annotation.SuppressLint
import android.os.Bundle
import com.example.statistics.R
import com.example.statistics.bean.FilesBean
import com.example.statistics.ex.download
import com.example.statistics.ex.isNetworkConnected
import com.example.statistics.net.callback.DownloadDialogHttpCallback
import com.example.statistics.utils.Constants
import com.example.statistics.utils.FileUtils
import com.example.statistics.utils.StatusBarUtil
import com.example.statistics.utils.permissions.PermissionsCheck
import com.jhj.httplibrary.HttpCall
import kotlinx.android.synthetic.main.activity_file_display.*
import org.jetbrains.anko.toast
import java.io.File
import java.net.URLDecoder


class FileDisplayActivity : BaseActivity() {
    override val title: String
        get() = "文件"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_file_display)
        StatusBarUtil.setLightMode(this)
        val fileBean = intent.getSerializableExtra(Constants.DATA) as FilesBean?//文件路径
        if (fileBean?.path == null) {
            toast("读取文件失败")
            return
        }

        PermissionsCheck.with(this)
                .requestPermissions(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .onPermissionsResult { _, _ ->
                    file_view.setOnGetFilePathListener {
                        val path = fileBean.path.replace("/upload", "")
                        val lastIndexOf = path.lastIndexOf("/")
                        val folder: String? = FileUtils.getSDPath(path.substring(0, lastIndexOf))
                        var localPath = folder + "/" + fileBean.name
                        localPath = URLDecoder.decode(localPath,"utf-8")
                        val localFile = File(localPath)
                        if (localFile.exists() && localFile.length() >= fileBean.size) {
                            file_view.displayFile(localFile)
                        } else {
                            localFile.createNewFile()
                            HttpCall.download(HttpCall.baseUrl + fileBean.path)
                                    .setUseBaseUrl(false)
                                    .enqueue(object : DownloadDialogHttpCallback(this, localFile,"加载中...") {
                                        override fun onSuccess(file: File) {
                                            file_view.displayFile(localFile)
                                        }

                                        override fun onFailure(msg: String) {
                                            toast(msg)
                                            if (localFile.exists()) {
                                                localFile.delete()
                                            }
                                        }
                                    })
                        }
                    }
                    file_view.show()
                }
    }

    @SuppressLint("CheckResult")
    fun fileDownLoad(downLoadUrl: String) {
        val index = downLoadUrl.lastIndexOf("/")
        val name = downLoadUrl.substring(index + 1, downLoadUrl.length)
        val file = File(FileUtils.FILE, name)
        if (isNetworkConnected()) {
            download(downLoadUrl, name, "正在加载中...") {
                file_view.displayFile(it)
            }
        } else if (file.exists()) {
            try {
                file_view.displayFile(file)
            } catch (e: Exception) {
                finish()
                toast("网络连接失败，请联网后重试")
            }
        } else {
            toast("文件打开失败")
            finish()
        }
    }

    public override fun onDestroy() {
        super.onDestroy()
        file_view.onStopDisplay()
    }
}
